package com.oj.auth.impl;

import com.oj.api.auth.AuthAPI;
import com.oj.api.auth.domain.AccountInfo;
import com.oj.api.auth.domain.UserGroupInfo;
import com.oj.api.auth.service.IAccountService;
import com.oj.api.auth.service.IUserGroupService;
import com.oj.auth.entity.AccountEntity;
import com.oj.auth.entity.UserGroupEntity;
import com.oj.auth.repository.IAccountRepository;
import com.oj.common.IServiceLayer;
import com.oj.common.InfoPage;
import com.oj.common.SystemTool;
import com.oj.common.constants.OperTypeEnum;
import com.oj.common.exception.BreezeeException;
import com.oj.common.util.BreezeeUtils;
import com.oj.common.util.ContextUtil;
import org.apache.catalina.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

/**
 * 用户组服务
 * Created by Bing on 2018/5/11.
 */
@Service(AuthAPI.BEAN_USER_GROUP_SERVICE)
public class UserGroupServiceImpl implements IUserGroupService {


    @Override
    public UserGroupInfo saveInfo(UserGroupInfo userGroupInfo) throws BreezeeException {
        if(userGroupInfo.getProperties().get("save")!=null){
            userGroupInfo.setOperType(OperTypeEnum.WRITE);
            userGroupInfo.setCode(SystemTool.getCode());
            UserGroupEntity entity = new UserGroupEntity().createWithInfo(userGroupInfo);
            entity.setCheckCode(BreezeeUtils.getRandomNumber(6));
            return entity.save();
        }
        if(userGroupInfo.getProperties().get("update")!=null){

            UserGroupEntity entity = new UserGroupEntity().buildOne(userGroupInfo.getCode()).findEntity();
            entity.setName(userGroupInfo.getName());
            entity.setRemark(userGroupInfo.getRemark());
            entity.save();
            return entity.buildInfo();
        }
        return null;
    }

    @Override
    public UserGroupInfo findInfoById(String id) throws BreezeeException {
        UserGroupEntity entity = new UserGroupEntity().buildOne(id).findEntity();
        if(entity==null){
            return null;
        }
        return entity.buildInfo();
    }

    @Override
    public List<UserGroupInfo> listInfos(UserGroupInfo userGroupInfo) {
        return new UserGroupEntity().createWithInfo(userGroupInfo).list();
    }

    @Override
    public InfoPage<UserGroupInfo> pageInfos(UserGroupInfo userGroupInfo) {
        return null;
    }

    @Override
    public void deleteInfo(String id) throws BreezeeException {
        new UserGroupEntity().buildOne(id).delete();
    }

    @Override
    public UserGroupInfo addProblemSetToUserGroup(UserGroupInfo userGroupInfo) {
        UserGroupEntity entity = new UserGroupEntity().buildOne(userGroupInfo.getCode()).findEntity();
        if(entity==null){
            return null;
        }
        final String[] problemSetName = {""};
        JdbcTemplate jdbcTemplate = ContextUtil.getBean("jdbcTemplate",JdbcTemplate.class);
        jdbcTemplate.query("select name from CORE_PROBLEM_SET where code = "+userGroupInfo.getProblemSetCodes(), new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet rs) throws SQLException {
                problemSetName[0] = rs.getString("name");
            }
        });
        if(entity.getProblemSetCodes()!=null&&entity.getProblemSetCodes().length()>0){
            String[] ss = entity.getProblemSetCodes().split(",");
            boolean flag = true;
            for (String s:ss) {
                if(s.substring(0,s.indexOf("-")).equals(userGroupInfo.getProblemSetCodes())){
                    flag = false;
                    break;
                }
            }
            if(flag){
                entity.setProblemSetCodes(entity.getProblemSetCodes()+","+userGroupInfo.getProblemSetCodes()+"-"+problemSetName[0]);
            }
        }else{
            entity.setProblemSetCodes(userGroupInfo.getProblemSetCodes()+"-"+problemSetName[0]);
        }
        entity.save();
        return entity.buildInfo();
    }

    @Override
    public UserGroupInfo addPinCodeToUserGroup(UserGroupInfo userGroupInfo) {
        UserGroupEntity entity = new UserGroupEntity().buildOne(userGroupInfo.getCode()).findEntity();
        if(entity==null){
            return null;
        }
        String pinCode = SystemTool.uuid().replaceAll("-","").substring(0,16)+"_"+BreezeeUtils.DATE_FORMAT_LONG.format(new Date());
        if(entity.getPinCodes()!=null&&entity.getPinCodes().length()>0){
            entity.setPinCodes(entity.getPinCodes()+","+pinCode);
        }else{
            entity.setPinCodes(pinCode);
        }
        entity.save();
        return entity.buildInfo();
    }

    @Override
    public UserGroupInfo deleteProblemSetFromUserGroup(UserGroupInfo userGroupInfo) {
        UserGroupEntity entity = new UserGroupEntity().buildOne(userGroupInfo.getCode()).findEntity();
        if(entity==null){
            return null;
        }
        if(!StringUtils.isEmpty(userGroupInfo.getProblemSetCodes())){
            String[] ss = entity.getProblemSetCodes().split(",");
            int index = -1;
            entity.setProblemSetCodes("");
            for(int i=0;i<ss.length;i++){
                String s = ss[i];
                if(s.startsWith(userGroupInfo.getProblemSetCodes()+"-")){
                    index = i;
                }else{
                    entity.setProblemSetCodes(entity.getProblemSetCodes()+ss[i]+",");
                }
            }
            if(entity.getProblemSetCodes().length()>0){
                entity.setProblemSetCodes(entity.getProblemSetCodes().substring(0,entity.getProblemSetCodes().length()-1));
            }
            entity.save();
            return entity.buildInfo();
        }
        return null;
    }

    @Override
    public UserGroupInfo deletePinCodeFromUserGroup(UserGroupInfo userGroupInfo) {
        UserGroupEntity entity = new UserGroupEntity().buildOne(userGroupInfo.getCode()).findEntity();
        if(entity==null){
            return null;
        }
        if(!StringUtils.isEmpty(userGroupInfo.getPinCodes())){
            String[] ss = entity.getPinCodes().split(",");
            int index = -1;
            entity.setPinCodes("");
            for(int i=0;i<ss.length;i++){
                String s = ss[i];
                if(s.startsWith(userGroupInfo.getPinCodes()+"_")){
                    index = i;
                }else{
                    entity.setPinCodes(entity.getPinCodes()+ss[i]+",");
                }
            }
            if(entity.getPinCodes().length()>0){
                entity.setPinCodes(entity.getPinCodes().substring(0,entity.getPinCodes().length()-1));
            }
            entity.save();
            return entity.buildInfo();
        }
        return null;
    }

    @Override
    public UserGroupInfo addAccountInfoToUserGroup(UserGroupInfo userGroupInfo) {

        UserGroupEntity entity = new UserGroupEntity().buildCode(userGroupInfo.getCode()).findEntity();
        if(entity==null){
            return null;
        }

        Set<String> codes = new HashSet<String>();
        entity.getUsers().forEach(a->{
            codes.add(a.getCode());
        });
        userGroupInfo.getUsers().forEach(a->{
            /**
             * 先创建学生用户
             */
            a.setCode("zua-"+a.getStudentNumber());
            AccountEntity accountEntity = new AccountEntity().buildCode(a.getCode()).findEntity();
            if(accountEntity==null){
                a.setOperType(OperTypeEnum.WRITE);
                accountEntity = new AccountEntity().createWithInfo(a);
                accountEntity.save();
            }
            if(!codes.contains(a.getCode())){
                AccountEntity ae = new AccountEntity().buildCode(a.getCode()).findEntity();
                if(ae!=null){
                    entity.addUser(ae);
                }
            }
        });
        entity.save();
        return entity.buildInfo();
    }

    @Override
    public UserGroupInfo deleteUserFromUserGroup(UserGroupInfo userGroupInfo) {

        UserGroupEntity entity = new UserGroupEntity().buildCode(userGroupInfo.getCode()).findEntity();
        if(entity==null){
            return null;
        }
        Set<AccountEntity> newUsers = new HashSet<>();
        entity.getUsers().forEach(a->{
            boolean flag = true;
            for(AccountInfo accountInfo:userGroupInfo.getUsers()){
                if(accountInfo.getCode().equals(a.getCode())){
                    flag = false;
                    break;
                }
            }
            if(flag){
                newUsers.add(a);
            }
        });

        entity.setUsers(newUsers);
        entity.save();
        return entity.buildInfo();
    }

    @Override
    public UserGroupInfo expertMarkForGetUserGroupInfo(String code) {
        UserGroupEntity entity = new UserGroupEntity().buildCode(code).findEntity();
        return entity.buildInfo();
    }

}
